package org.sean.framework.schedule.client;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.sean.framework.logging.Logger;
import org.sean.framework.schedule.ScheduleJob;
import org.sean.framework.util.GSONUtil;
import org.sean.framework.util.HttpUtil;
import org.sean.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * Schedule Service
 */
@Service
public class ScheduleClientImpl implements ScheduleClient {
    public static final String SUCCESS = "SUCCESS";
    public static final String UNKNOWN = "ERROR";
    public static final String FAILED = "FAILED";

    public static final Long TIMEOUT = 30 * 60 * 1000L;
    private static final String HTTP_URL = "http://" + "{0}" + ":" + "{1}" + "/actuator/jobs";
    private final Logger logger = Logger.newInstance(getClass());
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 客户端发起调用
     *
     * @param job 客户端发起请求
     */
    @Override
    public void send(ScheduleJob job, Map<String, String> headers) {
        ServiceInstance choose = loadBalancerClient.choose(job.getServiceName());
        if (choose == null) {
            logger.warn("任务执行失败,未能匹配到服务,任务ID：{}", job.getId());
            return;
        }
        String url = StringUtil.formatContent(HTTP_URL, choose.getHost(), String.valueOf(choose.getPort()));
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), GSONUtil.obj2Json(job));
        try {
            headers.put("Content-Type", "application/json");
            byte[] bytes = HttpUtil.post(url, Headers.of(headers), body);
            if (bytes == null) {
                logger.error("任务调用失败,服务不支持http调用,任务ID：{}", job.getId());
                return;
            }
            String result = new String(bytes, Charset.defaultCharset());
            logger.debug("http调用,任务执行结果:{},任务id:{}", result, job.getId());
            switch (result) {
                case SUCCESS:
                    logger.error("任务调用成功,任务ID：{}", job.getId());
                    break;
                case FAILED:
                    logger.error("任务调用失败,找不到对应的类或方法,任务ID：{}", job.getId());
                    break;
                default:
                    logger.error("任务调用失败,请查看日志获取详情,任务ID：{}", job.getId());
            }
        } catch (Exception e) {
            logger.error("任务调用失败,任务ID：{}", job.getId());
            logger.error(e);
        }
    }


}
